import { defineStore } from "pinia";
import { storage } from "../../utils";
import { ref } from "vue";
import { service } from "../service";

// 本地缓存
const useBrandStore = defineStore("brand", function () {

    // 列表
    const list = ref<any[]>([]);

    // 获取实时库存
    async function get(keyword = '', refresh?: boolean) {
        if (!refresh) {
            return list.value
        }
        return service.out.dbStock({ searchText: keyword })
            .then((res: any) => {
                if (res) {
                    set(res);
                }
                return res;
            })
    }

    // 设置
    function set(data: any) {
        list.value = data;
    }

    // 更新值
    function update(index?: any, data?: any) {
        const hlNoArr = selList.value.map((item: any) => item.blockNo)
        list.value.forEach((item: any) => {
            if (hlNoArr.includes(item.blockNo)) {
                item._isSelect = true
            } else {
                item._isSelect = false
            }
        })
    }

    // 已选择的荒料号
    const selList = ref<any[]>(storage.get("selList") || [])

    // 设置
    function setSelList(data: any, type?: any) {
        if (type == "update") {
            selList.value = data;

            storage.set("selList", selList.value);
            return false
        }

        const _index = selList.value?.findIndex((item: any) => item.blockNo == data.blockNo) ?? -1

        if (_index > -1) {
            selList.value[_index] = data
            // selList.value.splice(_index, 1)

            storage.set("selList", selList.value);
            return false
        }

        selList.value.push(data)

		storage.set("selList", selList.value);
    }

    // 删除
    function delSelList(index: any, data?: any) {
        selList.value.splice(index, 1)
    }

    // 清空已选择的荒料号
    function clearSelList() {
        selList.value = [];
        selObj.value = {}
    }

    // 当前选择得荒料号
    const selObj = ref<any>(storage.get("selObj") || {})

    function setSelObj(data: any) {
        selObj.value = data

		storage.set("selObj", selObj.value);
    }

    return {
        list,
        get,
        set,
        update,

        // 选择
        selList,
        setSelList,
        delSelList,
        clearSelList,

        // 选中
        selObj,
        setSelObj
    };
});

export default useBrandStore;
